/**
 * Created by kinfen on 16/9/5.
 */

const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const cssnano = require('gulp-cssnano');
const concat = require('gulp-concat');
const browserify = require('browserify');
const less  = require('gulp-less');
const source = require('vinyl-source-stream');

function initGulp(config){
    gulp.task('convertJS', function(){
        var stream = gulp.src(config.souceFolder + '/script/**/*')
            .pipe(babel({
                presets: ['es2015']
            })).on('error', function(error){
                console.log(error.toLocaleString());
                console.log('不能转换目标js');
                this.emit("end");
            })
            .pipe(uglify())
            .pipe(gulp.dest(config.destFolder + '/script')).on('finish', function(file){
                console.log('finish convert js file');
            });
        return stream;

    })
// 合并并压缩css
    gulp.task('convertCSS', function(){
        var lessobj = less();
        var stream = gulp.src(config.souceFolder + '/style/**/*')
            .pipe(lessobj).on('error', function(error){
                console.log(error.toLocaleString());
                console.log('不能转换目标js');
                this.emit("end");
            })
            .pipe(cssnano())
            .pipe(rename(function(path){
                path.basename += '.min';
            }))
            .pipe(gulp.dest(config.destFolder + '/style'))
            .on('finish', function(file){
                console.log('finish convert css file');
            });;

        return stream;

    })

// 监视文件变化，自动执行任务
    gulp.task('watch', function(){
        gulp.watch(config.souceFolder + '/style/**/*', ['convertCSS']);
        gulp.watch(config.souceFolder + '/script/**/*', ['convertJS', 'browserify']);
    })

// browserify
    gulp.task("browserify", function () {
        try{
            var b = browserify({
                entries: config.destFolder + "/script/app.js"
            });
            return b.bundle()
                .pipe(source(config.destJsName))
                .pipe(gulp.dest(config.destFolder + "/script")).on('finish', function(file){
                    console.log('finish build bundle js file');
                });;
        }
        catch(e)
        {
            console.log('不能完成bundlejs转换');
        }
    });
    gulp.task('start', ['convertJS', 'convertCSS', 'browserify', 'watch']);
}


var Tools = function(){

};
Tools.prototype.run = function (){
    var config = require('./package.json').config;
    if (config){
        gulp.start(config);
    }
}
Tools.prototype.start = function(config){
    initGulp(config);
    gulp.run("start");
}
var tool = new Tools();
tool.run();
module.exports = exports = new Tools();
